<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Cart;
use App\Models\Category;
use App\Models\MallProductStock;
use App\Models\Product;
use App\Models\Tag;
use App\Services\MallOrderService;
use Illuminate\Http\Request;

class ProductController extends BaseController
{
    public $model = Product::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $search = ['title' => '', 'category_id' => 0, 'on_status' => -1
            , 'start_at' => null, 'end_at' => null];
        $input = $request->input();
        $product_no = $input['product_no'] ?? null;
        $amount_min = $input['amount_min'] ?? null;
        $amount_max = $input['amount_max'] ?? null;
        $order_by_key = $request->input('order_by_key', 'id');
        $order_by_value = $request->input('order_by_value', 'desc');

        $list = Product::apply($search, $input)->when($amount_min, function ($q) use($amount_min){
            $q->where('amount', '>=', $amount_min * 100);
        })->when($amount_max, function ($q) use($amount_max){
            $q->where('amount', '<=', $amount_max * 100);
        })->when($product_no, function ($q) use($product_no){
            $q->where('product_no', 'like', '%' . $product_no . '%');
        })->withCertain('category', ['title'])->withCertain('parent_category', ['title'])->orderBy($order_by_key, $order_by_value)
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

    public function info(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
        ]);
        $id = $request->input('id');
        $product = Product::with('tags')->find ($id);
        if (!$product)
            return $this->failed('商品不存在');

        $product = $product->toArray();
        if ($product['is_specs']) {
            $specs_detail_info = $product['specs_detail_info'];
            foreach ($specs_detail_info as $key => &$item) {
                $stock = MallProductStock::where('product_id', $product['id'])->where('key', $key)->value('stock') ?: 0;
                $item['stock'] = $stock;
            }
            $product['specs_detail_info'] = $specs_detail_info;
            $product['specs_detail']['info'] = array_values($specs_detail_info);
        }
        return $this->success($product);
    }



    public function store(Request $request) {
        $this->validate($request, [
            'title' => 'required',
            'category_id' => 'required',
            'producer_id' => 'required',
            'fare' => 'filled|gte:0|lte:1000',
            'amount' => 'filled|gte:0|lte:1000000',
            'vip_amount' => 'filled|gte:0|lte:1000000',
            'id' => 'filled|exists:mall_products'
        ], [
            'category_id.required' => '请选择二级分类'
        ]);
        try {
            return \DB::transaction(function () use($request) {
                $input = $request->input();
                $input['amount'] = $input['amount_yuan']?? 0 ;
                $input['vip_amount'] = $input['vip_amount_yuan']?? 0 ;

                $arr_tag = json_decode($input['tag_ids']);
                $exist_new = Tag::whereIn('id', $arr_tag)->where('title', '新品')->exists();
                $input['is_new'] = $exist_new ? 1 : 0;

                //满减包邮
                $exist_reduction = Tag::whereIn('id', $arr_tag)->where('title', '满减包邮')->exists();
                $input['is_full_reduction'] = $exist_reduction ? 1 : 0;

                $category = Category::find($input['category_id']);
                if (!$category)
                    return $this->failed('分类id不存在');
                $input['parent_category_id'] = $category->parent_id;

                $temp = [];
                $is_specs = $request->input('is_specs', 0);
                if ($is_specs) {
                    $arr_specs_detail = json_decode($input['specs_detail'], true);
                    if (!empty($arr_specs_detail)) {
                        $specs_info_list = $arr_specs_detail['info'];
                        foreach ($specs_info_list as $item) {
                            $unique_key = MallOrderService::specsKey($item);
                            $temp[$unique_key] =  $item;
                        }
                        $input['specs_detail_info'] = json_encode_cn($temp);
                        $input['amount'] = min(array_column($arr_specs_detail['info'], 'amount')) * 100;
                        $input['vip_amount'] = min(array_column($arr_specs_detail['info'], 'vip_amount')) * 100;
                        $input['stock'] = array_sum(array_column($arr_specs_detail['info'], 'stock'));
                    }
                } else {
                    $input['amount'] =  $input['amount'] * 100;
                    $input['vip_amount'] = $input['vip_amount'] * 100;
                }
                $id = \request("id");
                if ($id) {
                    $product =  Product::find($id);
                    $product->update($input);
                } else {
                    $product = Product::create($input);
                    $id = $product->id;
                }
                if ($is_specs) {
                    $old_arr_key = MallProductStock::where('product_id', $id)->get()->pluck('key')->all();
                    $arr_key = array_keys($temp);
                    $arr_delete = array_diff($old_arr_key, $arr_key); //旧的里面有， 新的里面没有
                    //删除差集
                    MallProductStock::where('product_id', $product->id)->whereIn('key', $arr_delete)->delete();
                    //其他调用save
                    foreach ($temp as $unique_key => $val) {
                        $model = MallProductStock::where('product_id', $product->id)->where('key', $unique_key)->first();
                        if (!$model) {
                            $model = new MallProductStock();
                        }
                        $model->product_id = $product->id;
                        $model->key = $unique_key;
                        $model->stock = $val['stock'];
                        $model->save();
                    }
                    MallProductStock::flushQueryCache();
                }
                $product->tags()->sync($arr_tag);
                return $this->success($id);

            });
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->failed($e->getMessage());
        }
    }

    public function editSaleNum(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'fake_sale_num' => 'required',
        ]);
        $input = $request->input();
        $product = Product::find($input['id']);
        if (!$product)
            return $this->failed('销量不存在');
        $product->fake_sale_num = $input['fake_sale_num'];
        $product->save();
        return $this->success([]);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        try {
            return \DB::transaction(function () use($request) {
                $ids = $request->input('ids');
                $arr_id = explode(",", $ids);
                $this->model::whereIn('id', $arr_id)->delete();
                Cart::whereIn('product_id', $arr_id)->delete();
                return $this->success([]);
            });
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->failed($e->getMessage());
        }
    }

}

